#ifndef OCRTHREAD_H
#define OCRTHREAD_H

#include <QThread>
#include <qpixmap.h>

#include "ppocr/ocr_pub.h"
struct TextBox
{
    int line = 1;
    int flag = 1;
    bool isSelected = false;
    QRect rect;
    QString text;
    QVector<float> poslist;
    QVector<float> widthlist;
    TextBox():rect(QRect()),text(""){}
    TextBox(QRect a, QString b, QVector<float> c, QVector<float> d):rect(a),text(b),poslist(c),widthlist(d){}
    friend QDataStream& operator<<(QDataStream& out, const TextBox& obj)
    {
        out << obj.line << obj.flag << obj.isSelected << obj.rect << obj.text << obj.poslist << obj.widthlist;
        return out;
    }


    friend QDataStream& operator>>(QDataStream& in, TextBox& obj)
    {
        in >> obj.line >> obj.flag >> obj.isSelected >> obj.rect >> obj.text >> obj.poslist >> obj.widthlist;
        return in;
    }
};
struct DetBox
{
    QRect rect;
    QString text;
    QVector<float> color;
    DetBox():rect(QRect()),text(""){}
    DetBox(QRect a, QString b, QVector<float> c):rect(a),text(b),color(c){}
    friend QDataStream& operator<<(QDataStream& out, const DetBox& obj)
    {
        out << obj.rect << obj.text << obj.color;
        return out;
    }

    friend QDataStream& operator>>(QDataStream& in, DetBox& obj)
    {
        in >> obj.rect >> obj.text >> obj.color;
        return in;
    }
};
class OCRThread : public QThread
{
    Q_OBJECT
private:
    QString m_srcPath;
    QList<DetBox> m_detSet;
    QList<TextBox> m_cutBoxSet;
    QList<int> m_line_top_Set;
    QList<int> m_line_Set;
    QPixmap *m_pSrcImg;
    QPixmap m_img;
    bool m_isRunning;
    bool m_isPixmap;
    bool m_isCancel = false;
    int m_ocrId = 0;


    bool checkCanceled();
    QString loadCacheIfPossible();
    std::vector<OCRPredictResult> ocrTask();
    void preProcessOcrResults(QList<TextBox> &results, std::vector<OCRPredictResult> &ocr_result);
    void processOcrResults(QList<TextBox> &results);
    void saveCacheOrIndex(QString &key);
    void highlightText(QList<TextBox> &result);
    void objDetAndClas(QList<TextBox> &results);
    void objDetAndClasFromCache();
    void ocrImage();
public:
    ~OCRThread();
    OCRThread();
    void setCancel();
    QList<TextBox> &cutBoxSets();
    QList<int> &lineTopSets();
    QList<int> &lineSets();
    QPixmap &outImage();
    void setInputImage(QString path, QPixmap *img);
signals:
    void returnResult(int);
protected:
    void run();
};

#endif // OCRTHREAD_H
